package com.lemo.smart.thread;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 罗选通 on 2017/12/25.
 */
public class MyThreadLocal<T> {

  private Map<Thread, T> container = Collections.synchronizedMap(new HashMap<Thread, T>());

  public void set(T value) {
    container.put(Thread.currentThread(), value);
  }

  public T get() {
    Thread thread = Thread.currentThread();
    T t = container.get(thread);
    if (t == null && container.containsKey(thread)) {
      t = initialValue();
      container.put(thread, t);
    }
    return t;
  }

  public void remove() {
    container.remove(Thread.currentThread());
  }

  protected T initialValue() {
    return null;
  }
}
